package jam.network.message;

import jam.model.*;
import jam.network.*;
import java.util.*;

//
// =============================================================================
//

/**
 * Class for the login action.
 */
public class ClientActionLogin extends ClientCommand {
    protected static final String KEYWORD = "CA_LOGIN";

    private String username;
    private String password;
    
    //
    // =========================================================================
    //
    
    /**
     * Processes the message. Logs the user in and all that.
     */
    @Override
    public void process(ClientController t) {
        NetworkController c = t.getNetworkController();
        ServerModel server = c.getModel();
        ClientModel client = t.getModel();
                 
        boolean success = false;
        HashMap<String,String> credentials = new HashMap<String,String>();
		credentials.put("email",username);
		credentials.put("password",password);
        // This thread is already logged in?
        if (client.isLoggedIn() == false)    
	        if (User.exists(credentials)) // Do the credentials match?
		        if (server.isLoggedIn(this.username) == false) // Already logged in?
		            success = true;
        
        // Are we good to login?
        if (success) {
        	// Register with the controller that this user is connected
        	// via this thread, and also set in the threads model that
        	// it is logged in.
	        server.addLoggedIn(this.username, t);
	        client.setUser(new User(this.username, this.password));
		client.getUser().populate(credentials);
	}
        
        // Construct a response
        t.send(new ServerResponse(this, success));
    }
    
    //
    // =========================================================================
    //
    
    @Override
    protected String getKeyword() { 
        return ClientActionLogin.KEYWORD; 
    }
    
    //
    // =========================================================================
    //
    
    /**
     * Constructor. Processes the data string.
     *
     * @param transactionId The identification number for this particular message.
     * @param args A scanner with the arguments
     */
    protected ClientActionLogin(int transactionId, Scanner args) {
        super(transactionId);
        
        // Grab the supplied credentials.
        this.username = args.next();
        this.password = args.next();
    }
}
